//
//  MSMeVC.m
//  MS
//
//  Created by He Yuan on 13-2-6.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSMeVC.h"
#import "MSMeTopView.h"
#import "MSMeMenusView.h"
#import <QuartzCore/QuartzCore.h>
#import "MSFansVC.h"
#import "MSMeInfoVC.h"
#import "MSFavoritesListVC.h"
#import "EGORefreshTableHeaderView.h"
#import "MSMeCell.h"
#import "UIImageView+WebCache.h"

#import "MSPictureDetailVC.h"

#import "MSSettingVC.h"

#import "MSShowerDetailVC.h"
#import "MSEditUserInfo.h"

#import "MyFavListVC.h"


@interface MSMeVC ()<UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate,EGORefreshTableHeaderDelegate>
{
    UIScrollView *scrollView;
    MSMeTopView *topView;
    MSMeMenusView *menusView;
    UITableView *meTableView;
    BOOL _reloading;
    EGORefreshTableHeaderView *_refreshHeaderView;
    NSMutableArray *dataArr;
}
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)MSMeTopView *topView;
@property(nonatomic,strong)MSMeMenusView *menusView;
@property(nonatomic,strong)UITableView *meTableView;
@property(nonatomic,retain)NSMutableArray *dataArr;

- (void)reloadTableViewDataSource;

- (void)doneLoadingTableViewData;

@end

@implementation MSMeVC
@synthesize scrollView = _scrollView;
@synthesize topView = _topView;
@synthesize menusView = _menusView;
@synthesize meTableView = _meTableView;
@synthesize dataArr = _dataArr;
@synthesize isNeedRefresh;


- (id)init
{
    self = [super init];
    if (self)
    {
        isNeedRefresh = YES;
        
        _dataArr = [[NSMutableArray alloc]initWithObjects:nil,nil];
    }
    
    return self;
}


- (void)viewDidUnload
{
	self.scrollView = nil;
    self.topView = nil;
    self.menusView = nil;
    self.meTableView = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    _scrollView = nil;
	_topView = nil;
	_menusView = nil;
	_meTableView = nil;
}

-(void)loadView
{
    [super loadView];
    HYLog(@"loadView");

    _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    _scrollView.delegate = self;
    _scrollView.contentSize = self.view.bounds.size;
    [self.view addSubview:self.scrollView];
    
    _topView  = [[MSMeTopView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100)];
    [self.scrollView addSubview:self.topView];
    
    CGRect topViewFrame = self.topView.frame;
    CGPoint menusPoint ={topViewFrame.origin.x, topViewFrame.origin.y+topViewFrame.size.height};
    _menusView = [[MSMeMenusView alloc]initWithOrigin:menusPoint delegate:self];
    [self.scrollView addSubview:self.menusView];
    
    CGRect tableViewFrame = self.view.bounds;
    tableViewFrame.origin.y = self.menusView.frame.origin.y + self.menusView.frame.size.height;
    tableViewFrame.size.height = [UIScreen mainScreen].applicationFrame.size.height - self.tabBarController.tabBar.frame.size.height - self.menusView.frame.size.height - self.topView.frame.size.height;
    _meTableView = [[UITableView alloc]initWithFrame:tableViewFrame style:UITableViewStylePlain];
//    _meTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleBottomMargin;
    _meTableView.backgroundColor = [UIColor clearColor];
    _meTableView.backgroundView = nil;
    _meTableView.delegate = self;
    _meTableView.dataSource = self;
    [self.scrollView addSubview:self.meTableView];
    
    
    if (_refreshHeaderView == nil)
    {
		_refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.scrollView.bounds.size.height, self.view.frame.size.width, self.scrollView.bounds.size.height)];
		_refreshHeaderView.delegate = self;
		[self.scrollView addSubview:_refreshHeaderView];
	}
	
	//  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.topView refreshUI:[[MSSetting sharedSetting]getAccountInfo]];
    
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:NO];
    HYLog(@"viewWillAppear");
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if(isNeedRefresh)
    {
        isNeedRefresh = NO;
        [self performSelector:@selector(ViewFrashData) withObject:nil afterDelay:0.6];
    }
    
    HYLog(@"viewDidAppear");
}


- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    HYLog(@"viewWillLayoutSubviews");
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    HYLog(@"viewDidLayoutSubviews");
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setTitle:HYLocalizedString(@"我的空间") showBackButton:NO];
    [self setRightImageItem:@"me_setting"];
}


-(void)configureViews:(BOOL)animation
{
    [super configureViews:animation];
}


-(void)ViewFrashData
{
    [_scrollView setContentOffset:CGPointMake(0,-75) animated:YES];
    [self performSelector:@selector(doneManualRefresh) withObject:nil afterDelay:0.4];
}

-(void)doneManualRefresh
{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:self.scrollView];
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:self.scrollView];
}


-(void)rightBarButtonItemAction:(UIButton *)btn
{
    [self loadViewController:NSStringFromClass([MSSettingVC class]) hidesBottomBarWhenPushed:YES];
}

-(void)MenusClick:(UIButton *)btn
{
    switch (btn.tag) {
        case 0:
            [self loadViewController:NSStringFromClass([MSEditUserInfo class]) hidesBottomBarWhenPushed:YES];
            break;
        case 1:
            [self loadViewController:NSStringFromClass([MyFavListVC class]) hidesBottomBarWhenPushed:YES];
            break;
        case 2:
            [self loadViewController:NSStringFromClass([MSFansVC class]) hidesBottomBarWhenPushed:YES];
            break;
        case 3:
            //more
            break;
        default:
            break;
    }
}

-(void)updateUI
{
    [self.topView refreshUI:[[MSSetting sharedSetting]getAccountInfo]];

    [self.meTableView reloadData];
    CGRect tableViewFrame = self.meTableView.frame;
    if (self.meTableView.contentSize.height > tableViewFrame.size.height)
    {
        tableViewFrame.size.height = self.meTableView.contentSize.height;
        self.meTableView.frame = tableViewFrame;
    }
    [self.scrollView setContentSize:CGSizeMake(0,self.meTableView.frame.origin.y + self.meTableView.frame.size.height)];
    [self.meTableView flashScrollIndicators];
}

-(void)requestData
{
    NSDictionary *p =  [NSDictionary dictionaryWithObjectsAndKeys:
                        [[MSSetting sharedSetting]getAccountID],@"uid",
                        [[MSSetting sharedSetting]getAccountID],@"l_uid",
                        nil];
    [WebService getRequestAction:APIUserHome
                           param:p
                         success:^(NSDictionary *info,NSError *error)
     {
         if (error == nil && info)
         {
             HYLog(@"%@",info);
             
             NSDictionary *content = [info objectForKey:@"result"];
             
             //update userinfo
             NSMutableDictionary *userinfo = [NSMutableDictionary dictionaryWithDictionary:[[MSSetting sharedSetting]getAccountInfo]];
             if ([content objectForKey:@"a_count"])
             {
                 [userinfo setObject:[content objectForKey:@"a_count"] forKey:@"a_count"];
             }
             if ([content objectForKey:@"f_count"])
             {
                 [userinfo setObject:[content objectForKey:@"f_count"] forKey:@"f_count"];
             }
             if ([content objectForKey:@"avatar"])
             {
                 [userinfo setObject:[content objectForKey:@"avatar"] forKey:@"avatar"];
             }
             [[MSSetting sharedSetting]setAccountInfo:userinfo];

             
             NSArray *user_pic_list = [content objectForKey:@"user_pic_list"];
             NSString *username = [content objectForKey:@"user_name"];
             if (user_pic_list && [user_pic_list count]>0)
             {
                 [_dataArr removeAllObjects];
                 for (int i = 0 ; i < [user_pic_list count]; i++)
                 {
                     NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[user_pic_list objectAtIndex:i]];
                     [dict setObject:username forKey:@"user_name"];
                     [_dataArr addObject:dict];
                     dict = nil;
                 }
             }
             [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
         }
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
     } failure:^(id info ,NSError *error){
         [MSTool showError:error];
         [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:0.5];
     } progress:nil];
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods
- (void)reloadTableViewDataSource
{
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
    [self requestData];
}

- (void)doneLoadingTableViewData
{
	//  model should call this when its done loading
	_reloading = NO;
    NSDate * date = [NSDate date];
    [[NSUserDefaults standardUserDefaults] setValue:date forKey:@"EGORefreshTableView_MSMe_LastRefresh"];
    [[NSUserDefaults standardUserDefaults] synchronize];
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.scrollView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)sc{
	[_refreshHeaderView egoRefreshScrollViewDidScroll:sc];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)sc willDecelerate:(BOOL)decelerate{
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:sc];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
    NSDate *date =  [[NSUserDefaults standardUserDefaults] valueForKey:@"EGORefreshTableView_MSMe_LastRefresh"];
    if (date == nil)date = [NSDate date];
	return date; // should return date data source was last changed
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArr count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat baseHeight = 297;
    return baseHeight + CELL_TXTLBL_HEIGHT([[_dataArr objectAtIndex:indexPath.row] objectForKey:@"content"]);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    MSMeCell *cell = (MSMeCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[MSMeCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *item = [_dataArr objectAtIndex:indexPath.row];
    NSString *time =  [item objectForKey:@"create_time"];
    [(UILabel *)[cell.timeBtn viewWithTag:1] setText:time];
    cell.likeCountLbl.text =  [item objectForKey:@"collect_count"];
    cell.commentCountLbl.text =  [item objectForKey:@"comment_count"];
    [cell.imageAndTxtView setText:[item objectForKey:@"content"]];
    [cell.imageAndTxtView setContentImage:[item objectForKey:@"thumb"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MSShowerDetailVC *vc  = [[MSShowerDetailVC alloc]initWithDatas:_dataArr currentIndex:indexPath.row];
//    MSPictureDetailVC *vc = [[MSPictureDetailVC alloc]initWithImages:_dataArr currentIndex:indexPath.row];
    [vc setHidesBottomBarWhenPushed:YES];
    [(TabBarViewController *)self.tabBarController setCustomTabBarHidden:YES];
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
